package com.etc.security.filter;

import java.io.IOException;
import java.util.Collections;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.security.config.JwtTokenUtils;
import org.slf4j.Logger;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import com.etc.common.Code;
import com.etc.common.CodeMessage;
import com.etc.security.exception.TokenIsExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * Filename:    JWTAuthorizationFilter.java  
 * Description:   basic认证过滤器-后置
 * Copyright:   Copyright (c) 2018-2019 All Rights Reserved.
 * Company:     chinasofti.com Inc.
 * @author:     mazheng 
 * @version:    1.0  
 * Create at:   2020年3月4日 下午3:38:35  
 *  
 * Modification History:  
 * Date         Author      Version     Description  
 * ------------------------------------------------------------------  
 * 2020年3月4日      mazheng      1.0         1.0 Version  
 *
 */
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(JWTAuthorizationFilter.class);
    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        a1:if (tokenHeader == null || tokenHeader.equals("")) {
            if (request.getCookies() != null)
            for (Cookie cookie : request.getCookies()) {
                if (JwtTokenUtils.TOKEN.equals(cookie.getName())) {
                    tokenHeader = cookie.getValue();
                    break a1;
                }
            }
            if (request.getParameter("token") != null) {
                tokenHeader = request.getParameter("token");
            }
        }
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            //返回json形式的错误信息
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("application/json; charset=utf-8");
//            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//            response.getWriter().write(new ObjectMapper().writeValueAsString( CodeMessage.faild(Code.FAIL, "超时")));
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        try {
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        } catch (TokenIsExpiredException e) {
            //返回json形式的错误信息
            e.printStackTrace();
            logger.warn(e.getMessage());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
//            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(new ObjectMapper().writeValueAsString( CodeMessage.faild(Code.FAIL_RELOGIN, "Token超时，请重新登录")));
            return;
        }
        super.doFilterInternal(request, response, chain);
    }

    // 这里从token中获取用户信息并新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) throws TokenIsExpiredException {
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        if (expiration) {
            throw new TokenIsExpiredException("token超时了");
        } else {
            String username = JwtTokenUtils.getUsername(token);
            String role = JwtTokenUtils.getUserRole(token);
            if (username != null) {
                return new UsernamePasswordAuthenticationToken(username, null,
                        Collections.singleton(new SimpleGrantedAuthority(role))
                );
            }
        }
        return null;
    }
}
